<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>权限管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card>
			<!-- 添加角色按钮 -->
			<el-button @click='addRoles' type="primary">添加角色</el-button>
			<!-- 角色列表 -->
			<el-table :data="rolelist" border stripe>
				<!-- 展开列 -->
				<el-table-column type="expand">
					<template slot-scope="scope">
						<!--  -->
						<el-row :class="['bdbottom',i1===0?'bdtop':'','vcenten']"
							v-for="(item1,i1) in scope.row.children" :key="item1.id">
							<!-- 一级权限 -->
							<el-col :span="5">
								<el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}
								</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<!-- 二级权限 -->
							<el-col :span="19">
								<el-row :class="[i2===0?'':'bdtop','vcenten']" v-for="(item2,i2) in item1.children"
									:key='item2.id'>
									<el-col :span='6'>
										<el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">
											{{item2.authName}}</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
									<el-col :span="18">
										<el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning"
											v-for="(item3,i3) in item2.children" :key='item3.id'>
											{{item3.authName}}
										</el-tag>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
					</template>
				</el-table-column>
				<!-- 索引列 -->
				<el-table-column type="index"></el-table-column>
				<el-table-column label="角色名称" prop="roleName"></el-table-column>
				<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button size="mini" @click='modifyroles(scope.row)' type="primary" icon="el-icon-edit">编辑
						</el-button>
						<el-button size="mini" @click="deleteroles(scope.row)" type="danger" icon="el-icon-delete">删除
						</el-button>
						<el-button @click='showSetRightDialog(scope.row)' size="mini" type="warning"
							icon="el-icon-setting">分配权限</el-button>
					</template>
				</el-table-column>

			</el-table>
		</el-card>

		<el-dialog title="分配角色" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClose()">
			<el-tree ref="treeRef" :default-checked-keys="defKeys" :data="rightslist" :props="treeProps" show-checkbox
				node-key="id" default-expand-all></el-tree>
			<span slot="footer" class="dialog-footer">
				<el-button @click="setRightDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="allotRights()">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 添加角色对话框 -->
		<el-dialog @close="addrolesDialogClose" title="添加角色" :visible.sync="rolesVisible" width="50%">
			<el-form :model="rolesForm" :rules="rolesFormRules" ref="rolesFormRef" label-width="100px"
				class="demo-ruleForm">
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="rolesForm.roleName"></el-input>
				</el-form-item>
				<el-form-item label="角色描述" prop="roleDesc">
					<el-input v-model="rolesForm.roleDesc"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="rolesVisible = false">取 消</el-button>
				<el-button type="primary" @click="addroles">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 修改角色对话框 -->
		<el-dialog @close="midifrolesDialogClose" title="修改角色" :visible.sync="midifRolesDialogVisible" width="50%">
			<el-form :model="modifyrolesForm" :rules="modifyrolesFormRules" ref="modifyrolesFormRef"
				label-width="100px">
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="modifyrolesForm.roleName"></el-input>
				</el-form-item>
				<el-form-item label="角色描述" prop="roleDesc">
					<el-input v-model="modifyrolesForm.roleDesc"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="midifRolesDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="midifroles">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import roleApi from '../../request/power/roles.js'
export default {
  data () {
    return {
      rolelist: [],
      setRightDialogVisible: false,
      // 权限数据
      rightslist: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: null,
      // 添加角色对话框变量
      rolesVisible: false,
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      rolesFormRules: {
        roleName: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        roleDesc: [{
          required: true,
          message: '请输入角色描述',
          trigger: 'blur'
        }]
      },
      midifRolesDialogVisible: false,
      modifyrolesForm: {
        roleName: '',
        roleDesc: ''
      },
      modifyrolesFormRules: {
        roleName: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        roleDesc: [{
          required: true,
          message: '请输入角色描述',
          trigger: 'blur'
        }]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const {
        data: res
      } = await roleApi.roleApiGetList() // this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }
      this.rolelist = res.data
    },
    async removeRightById (role, id) {
      const configResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (configResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const {
        data: res
      } = await roleApi.roleApiDelete(`roles/${role.id}/rights/${id}`) // this.$http.delete(`roles/${role.id}/rights/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // this.getRolesList()
      role.children = res.data
    },
    async showSetRightDialog (role) {
      this.roleId = role.id
      // 获取权限列表数据
      const {
        data: res
      } = await roleApi.roleApiGetThree() // this.$http.get('/rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rightslist = res.data
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    setRightDialogClose () {
      this.defKeys = []
    },
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {
        data: res
      } = await roleApi.roleApiPostAll(`roles/${this.roleId}/rights`, { rids: idStr })
      // this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    // 添加角色展示对话框
    addRoles () {
      this.rolesVisible = true
    },
    addrolesDialogClose () {
      this.$refs.rolesFormRef.resetFields()
    },
    // 添加角色
    addroles () {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const {
          data: res
        } = await roleApi.roleApiPostAdd(this.rolesForm)
        // this.$http.post('roles', this.rolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        this.rolesVisible = false
        this.getRolesList()
      })
    },
    modifyroles (data) {
      console.log(data.id)
      this.modifyrolesForm.id = data.id
      this.modifyrolesForm.roleName = data.roleName
      this.modifyrolesForm.roleDesc = data.roleDesc
      this.midifRolesDialogVisible = true
    },
    midifrolesDialogClose () {
      this.$refs.modifyrolesFormRef.resetFields()
    },
    midifroles () {
      this.$refs.modifyrolesFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const url = `roles/${this.modifyrolesForm.id}`
        const dates = { roleName: this.modifyrolesForm.roleName, roleDesc: this.modifyrolesForm.roleDesc }
        const {
          data: res
        } = await roleApi.roleApiPutUpload(url, dates)
        /* this.$http.put(`roles/${this.modifyrolesForm.id}`, {
						roleName: this.modifyrolesForm.roleName,
						roleDesc: this.modifyrolesForm.roleDesc
					}) */
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败！')
        }
        this.$message.success('修改角色成功！')
        this.midifRolesDialogVisible = false
        this.getRolesList()
      })
    },
    async deleteroles (scope) {
      const configResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (configResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const url = `/roles/${scope.id}`
      // console.log(scope)
      const { data: res } = await roleApi.roleApiDeleteById(url) // this.$http.delete(`/roles/${scope.id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRolesList()
    }
  }
}
</script>

<style>
</style>
